package org.dbstar.scheduler.job;

import java.util.Map;

import org.dbstar.scheduler.beans.Job;
import org.dbstar.scheduler.beans.JobConf;
import org.dbstar.scheduler.control.JobConfController;
import org.dbstar.scheduler.control.JobController;
import org.dbstar.scheduler.control.exception.DaoException;
import org.dbstar.scheduler.identifier.Identifier;
import org.dbstar.scheduler.identifier.IdentifierFactory;


/**
 * 默认的Job工厂类实现
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-3-29
 */
public final class DefaultSchedulerFactory implements SchedulerFactory {
	private final IdentifierFactory identifierFactory;
	private final JobController jobController;
	private final JobConfController jobConfController;
	private final Map<String, JobFactoryRegister> factoryMap;

	public DefaultSchedulerFactory(IdentifierFactory identifierFactory, JobController jobController,
			JobConfController jobConfController, Map<String, JobFactoryRegister> factoryMap) {
		super();
		this.identifierFactory = identifierFactory;
		this.jobController = jobController;
		this.jobConfController = jobConfController;
		this.factoryMap = factoryMap;
	}

	@Override
	public Job createJob(Identifier jobConfIdentifier, Map<String, String> parameters, String submitter)
			throws IllegalFactoryException {
		JobConf conf;
		try {
			conf = jobConfController.getJobConf(jobConfIdentifier);
		} catch (DaoException e) {
			throw new IllegalFactoryException("Create job fail.", e);
		}
		if (conf == null) {
			throw new IllegalFactoryException("Create job fail. job conf is null.");
		}
		JobFactoryRegister register = factoryMap.get(conf.getType());
		if (register != null) {
			Job job = register.getJobFactory().createJob(this, conf, submitter, parameters);
			job.setReady(true);
			return job;
		} else {
			throw new IllegalFactoryException("Create job fail. Unkonwn job conf type: " + conf.getType());
		}
	}

	@Override
	public JobRunner createJobRunner(Job job) throws IllegalFactoryException {
		if (job == null) {
			throw new IllegalFactoryException("Create job runner fail. job is null.");
		}
		JobFactoryRegister register = factoryMap.get(job.getType());
		if (register != null) {
			return register.getJobRunnerFactory().createJobRunner(jobController, job);
		} else {
			throw new IllegalFactoryException("Create job runner fail. Unkonwn job type: " + job.getType());
		}
	}

	@Override
	public String getSystemIdentifier() {
		return identifierFactory.getSystemIdentifier();
	}
}
